package algocasts;

public class P52_removeNthFromEnd {
    class ListNode {
        int val;
        ListNode next;

        ListNode(int val) {
            this.val = val;
        }
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode vnode = new ListNode(0), fast = vnode, low = vnode;
        vnode.next = head;
        // 快指针先走 n 步
        for (; n > 0 && fast.next != null; n--) fast = fast.next;
        if (n != 0) return vnode.next;
        // 快指针 慢指针 同时走 直到快指针到末尾，
        while (fast.next != null) {
            fast = fast.next;
            low = low.next;
        }
        // 慢指针此时指向的是要删除的节点的前一个节点，
        low.next = low.next.next;
        return vnode.next;
    }
}
